package com.i2works.smartluolong.manageapi.controller.admin;


import com.i2works.smartluolong.manage.entity.admin.AdminUserDO;
import com.i2works.smartluolong.manage.service.admin.IAdminUserService;
import com.i2works.smartluolong.manageapi.utils.BaseModule;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 管理员账号基础
 *
 * @author koal <koal@vip.qq.com>
 * @date 2015年11月3日 下午8:35:20
 */
@RestController
@RequestMapping("/admin")
public class AdminController extends BaseModule {

    private final IAdminUserService adminUserService;

    @Autowired
    public AdminController(IAdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }


    /**
     * 登陆页面
     */
    @PostMapping(value = {"/login", "/index"})
    public Result login(
            @RequestParam(value = "userName", required = false) String userName,
            @RequestParam(value = "password", required = false) String password,
            HttpServletRequest request) {
        //判断账号密码是否为空
        if (StringUtils.isAnyBlank(userName, password)) {
            return R.error(MsgEnum.ACCESS_EMPTY.getMsg());
        }
        try {
            AdminUserDO adminUser = new AdminUserDO();
            adminUser.setUserName(userName);
            adminUser.setPassword(password);
            adminUser.setLoginIp(BaseUtils.getIP(request));
            adminUser.setLoginTime(new Date());
            return adminUserService.queryAppLoginUser(adminUser);
        } catch (ServiceException e) {
            logger.error("登录异常：" + e.getMessage());
            return R.error(MsgEnum.ACCESS_LOGIN_FAIL.getMsg());
        }
    }

    /**
     * 修改密码
     */
    @PostMapping(value = "/password")
    public Result updatePasswordChange(@ModelAttribute AdminUserDO adminUser) {
        Result result = new Result();
        try {
            adminUser.setUpdateName(getUserName());
            adminUserService.updatePasswordChange(adminUser);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.SAVE_ERROR.getMsg());
        }
        return result;
    }


    /**
     * 退出登陆
     */
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return R.success();
    }

}
